package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.igas.service.PDstChannelInfoService;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.*;
import cc.rengu.redp.bizimpl.upmp.dao.BCardBlacklistInfoMapper;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @author lizk
 */
@Service
@DS("upmp")
public class BCardBlacklistInfoServiceImpl extends ServiceImpl<BCardBlacklistInfoMapper, BCardBlacklistInfo> implements IBCardBlacklistInfoService {

    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IUpmpOrganizationService organizationService;
    @Autowired
    private IUpmpPrivilegeCheckService authPrivilegeCheckService;
    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    private IBizHisService bizHisService;
    @Autowired
    private PDstChannelInfoService pDstChannelInfoService;

    @Override
    public IPage<BCardBlacklistInfo> findByPage(QueryRequest queryRequest, BCardBlacklistInfo cardBlacklistInfo) {
        try {
            LambdaQueryWrapper<BCardBlacklistInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (!StringUtils.isEmpty(cardBlacklistInfo.getInstId())) {
                queryWrapper.eq(BCardBlacklistInfo::getInstId, cardBlacklistInfo.getInstId());
            }
            if (!StringUtils.isEmpty(cardBlacklistInfo.getAcctNo())) {
                queryWrapper.and(i -> i.like(BCardBlacklistInfo::getAcctNo, cardBlacklistInfo.getAcctNo()));
            }

            Page<BCardBlacklistInfo> page = new Page<>();
            SortUtil.handlePageSort(queryRequest, page, true);
            Page<BCardBlacklistInfo> infoPage = this.page(page, queryWrapper);

            return infoPage;
        } catch (Exception e) {
            log.error("获取卡号黑名单信息失败", e);
            return null;
        }
    }

    @Override
    public void createCardBlack(BCardBlacklistInfo cardBlacklistInfo) throws RedpException {
        saveData(cardBlacklistInfo);
    }

    @Override
    public void updateCardBlack(BCardBlacklistInfo cardBlacklistInfo) throws RedpException {
        saveData(cardBlacklistInfo);
    }

    private void saveData(BCardBlacklistInfo entity) throws RedpException {
        String flag = entity.getOptFlag();
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpOrganization org = organizationService.getOrgByCode(user.getOrgCode(), user.getInstId());

        //
        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(flag)) {
            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "cardBlacklistInfo:add");
            //
            entity.setId(null);
            entity.setValidStatus("01");
            entity.setOprId(user.getId());
            entity.setCreateTime(lastUpddt);
            entity.setLastOprId(user.getId());
            entity.setLastUpdateTime(lastUpddt);
            //
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                entity.setCardBlacklistStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
                this.save(entity);

                bizTmpService.saveBizTmp(entity, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(pDstChannelInfoService.getOprMenuId()), pDstChannelInfoService.getOprMenuName(),
                        entity.getCardBlacklistStatus(), entity.getAuditStatus(), entity.getId(), "", null, null, null);
            } else {
                entity.setCardBlacklistStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                this.save(entity);

                bizHisService.saveBizHisNew(entity, entity, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(pDstChannelInfoService.getOprMenuId()), pDstChannelInfoService.getOprMenuName(),
                        entity.getId(), null, null, null);
            }
        } else if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(flag)) {
            String id = entity.getId();
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }

            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "cardBlacklistInfo:edit");
            BCardBlacklistInfo dbCardBlackListInfo = this.getById(id);
            BCardBlacklistInfo cardBlackListInfo = new BCardBlacklistInfo();
            BeanUtils.copyProperties(entity, cardBlackListInfo);

            entity.setLastOprId(user.getId());
            entity.setLastUpdateTime(lastUpddt);
            entity.setCardBlacklistStatus(dbCardBlackListInfo.getCardBlacklistStatus());
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                dbCardBlackListInfo.setLastOprId(user.getId());
                dbCardBlackListInfo.setLastUpdateTime(lastUpddt);
                dbCardBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());

                this.saveOrUpdate(dbCardBlackListInfo);

                //检查临时表是否有数据，如果没用则新增
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                BeanUtils.copyProperties(entity, dbCardBlackListInfo);

                bizTmpService.saveBizTmp(dbCardBlackListInfo, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(pDstChannelInfoService.getOprMenuId()), pDstChannelInfoService.getOprMenuName(),
                        dbCardBlackListInfo.getCardBlacklistStatus(), dbCardBlackListInfo.getAuditStatus(), dbCardBlackListInfo.getId(), "", null, null, null);

            } else {
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());

                BeanUtils.copyProperties(entity, cardBlackListInfo);
                this.saveOrUpdate(cardBlackListInfo);

                //历史表新增
                bizHisService.saveBizHisNew(cardBlackListInfo, dbCardBlackListInfo, user, user.getInstId(),
                        BizOprEnum.OPR_UPDATE.getType(), lastUpddt, String.valueOf(pDstChannelInfoService.getOprMenuId()),
                        pDstChannelInfoService.getOprMenuName(), dbCardBlackListInfo.getId(), null, null, null);
            }
        } else if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(flag)
                || PageOptFlagEnum.OPT_FLAG_USE.getType().equals(flag)
                || PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(flag)) {
            String id = entity.getId();
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }
            BCardBlacklistInfo cardBlackListInfo = this.getById(id);

            if (Common.isBlank(cardBlackListInfo)) {
                log.error("根据id没有找到指定数据！");
                throw new RedpException("根据id没有找到指定数据!");
            }
            UpmpPrivilegeCheck privilegeCheck = new UpmpPrivilegeCheck();
            String bizOpr = "";
            if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(flag)) {
                bizOpr = BizOprEnum.OPR_STOP.getType();
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "cardBlacklistInfo:stop");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    cardBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType());
                } else {
                    cardBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                }
            } else if (PageOptFlagEnum.OPT_FLAG_USE.getType().equals(flag)) {

                bizOpr = BizOprEnum.OPR_USE.getType();
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "cardBlacklistInfo:use");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    cardBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType());
                } else {
                    cardBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                }
            } else if (PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(flag)) {

                bizOpr = BizOprEnum.OPR_CANCEL.getType();
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "cardBlacklistInfo:cancel");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    cardBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType());
                } else {
                    cardBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                }
            }
            cardBlackListInfo.setLastOprId(user.getId());
            cardBlackListInfo.setCardBlacklistStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
            cardBlackListInfo.setLastUpdateTime(lastUpddt);
            this.saveOrUpdate(cardBlackListInfo);

            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //检查临时表是否有数据，如果没用则新增
                bizTmpService.saveBizTmp(cardBlackListInfo, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(pDstChannelInfoService.getOprMenuId()), pDstChannelInfoService.getOprMenuName(),
                        cardBlackListInfo.getCardBlacklistStatus(), cardBlackListInfo.getAuditStatus(), cardBlackListInfo.getId(), "", null, null, null);

            } else {
                //历史表新增
                bizHisService.saveBizHisNew(entity, cardBlackListInfo, user, user.getInstId(),
                        BizOprEnum.OPR_UPDATE.getType(), lastUpddt, String.valueOf(pDstChannelInfoService.getOprMenuId()),
                        pDstChannelInfoService.getOprMenuName(), cardBlackListInfo.getId(), null, null, null);
            }
        } else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(flag)) {

            String id = entity.getId();
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }

            //获取临时表数据并转换成实体对象
            BizTmp tmp = bizTmpService.getBizTmpDetail(id);
            if (Common.isBlank(tmp)) {
                log.error("根据id没有找到指定临时表数据！");
                throw new RedpException("根据id没有找到指定临时表数据!");
            }
            String bizdata = "";
            if (null != tmp.getBizData1()) {
                bizdata += tmp.getBizData1();
            }
            if (null != tmp.getBizData2()) {
                bizdata += tmp.getBizData2();
            }
            if (null != tmp.getBizData3()) {
                bizdata += tmp.getBizData3();
            }
            // 临时表数据
            BCardBlacklistInfo cardBlackListInfoNew = JSON.parseObject(bizdata, BCardBlacklistInfo.class);
            // 正式表数据
            BCardBlacklistInfo cardBlackListInfo = this.getById(id);
            // 备份正式表数据
            BCardBlacklistInfo cardBlackListInfoOld = new BCardBlacklistInfo();
            BeanUtils.copyProperties(cardBlackListInfo, cardBlackListInfoOld);

            if (Common.isBlank(cardBlackListInfo) && !BizOprEnum.OPR_ADD.equals(tmp.getBizOpr())) {
                log.error("根据id没有找到指定数据！");
                throw new RedpException("根据id没有找到指定数据！");
            }

            String opt = entity.getOpt();
            if (Common.isBlank(opt)) {
                log.error("请求参数(opt)异常!");
                throw new RedpException("请求参数(opt)异常!");
            }
            //
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                // 审批通过将临时表数据更新到正式表
                BeanUtils.copyProperties(cardBlackListInfoNew, cardBlackListInfo);
            } else {
                String auditRefuseReason = entity.getAuditRefuseReason();
                cardBlackListInfo.setAuditRefuseReason(auditRefuseReason);
            }

            String bizOpr = "";
            if (BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType().equals(cardBlackListInfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    cardBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                    cardBlackListInfo.setCardBlacklistStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    cardBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_ADD.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType().equals(cardBlackListInfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    cardBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                    cardBlackListInfo.setCardBlacklistStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
                } else {
                    cardBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_CANCEL.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType().equals(cardBlackListInfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    cardBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                    cardBlackListInfo.setCardBlacklistStatus(BizDataStatusEnum.STATUS_STOPED.getType());
                } else {
                    cardBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_STOP.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType().equals(cardBlackListInfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    cardBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                    cardBlackListInfo.setCardBlacklistStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    cardBlackListInfo.setCardBlacklistStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_USE.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(cardBlackListInfo.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    cardBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                    cardBlackListInfo.setCardBlacklistStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    cardBlackListInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_UPDATE.getType();
            }
            // 状态赋值完成后，入库正式表
            this.saveOrUpdate(cardBlackListInfo);
            //
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                //审批通过将正式表更新到历史表
                bizHisService.saveBizHisNew(cardBlackListInfo, cardBlackListInfoOld, user, user.getInstId(),
                        BizOprEnum.OPR_UPDATE.getType(), lastUpddt, String.valueOf(pDstChannelInfoService.getOprMenuId()),
                        pDstChannelInfoService.getOprMenuName(), cardBlackListInfo.getId(), null, null, null);

            }
            // 修改临时表的审核状态等字段
            bizTmpService.saveBizTmp(cardBlackListInfo, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                    String.valueOf(pDstChannelInfoService.getOprMenuId()), pDstChannelInfoService.getOprMenuName(),
                    cardBlackListInfo.getCardBlacklistStatus(), cardBlackListInfo.getAuditStatus(), cardBlackListInfo.getId(), "", null, null, null);
        }
    }
}
